// pages/creator/profile.js
Page({
  data: {
    real_name: '',
    phone: '',
    gender: 0,
    genderList: [
      { _id: 0, label: '保密' },
      { _id: 1, label: '男' },
      { _id: 2, label: '女' },
    ]
  },
  onLoad(options) {
    this.loadProfile();
  },
  async loadProfile() {
    const res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_user',
        data: { funcName: 'getProfile' },
        success: (r) => resolve(r.result)
      })
    })
    this.setData({ real_name: res.data.real_name, phone: res.data.phone, gender: res.data.gender })
  },
  onSelectGender(ev) {
    const gender = parseInt(ev.detail.value);
    this.setData({ gender })
  },
  async onSubmit() {
    const real_name = this.data.real_name.trim(), gender = this.data.gender, phone = this.data.phone;
    if (real_name != '' && /^1[3456789]\d{9}$/.test(phone)) {
      const res = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_user',
          data: {
            funcName: 'update',
            updData: { real_name, gender, phone }
          },
          success: (r) => resolve(r.result)
        })
      })
      if (res.stats.updated > 0) {
        wx.showToast({
          title: '信息已更新',
          icon: 'none'
        })
        setTimeout(() => wx.navigateBack(), 500)
      }
    } else {
      wx.showToast({
        title: '字段未正确填写',
        icon: 'none'
      })
    }
  }
})